package com.itfreer.gather;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureQueryResult;
import com.esri.arcgisruntime.data.FeatureTable;
import com.esri.arcgisruntime.data.Field;
import com.esri.arcgisruntime.data.Geodatabase;
import com.esri.arcgisruntime.data.GeodatabaseFeatureTable;
import com.esri.arcgisruntime.geometry.Geometry;
import com.esri.arcgisruntime.geometry.GeometryEngine;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.Polygon;
import com.esri.arcgisruntime.geometry.Polyline;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.layers.Layer;
import com.esri.arcgisruntime.loadable.LoadStatus;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.LocationDisplay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.itfreer.arcgis.FeatureTableUtils;
import com.itfreer.arcgis.GeodatabaseUtils;
import com.itfreer.arcgis.LayerUtils;
import com.itfreer.arcgis.MapUtils;
import com.itfreer.arcgis.MapViewUtils;
import com.itfreer.arcgis.edit.DrawFreePolyLineTool;
import com.itfreer.arcgis.edit.DrawFreePolygonTool;
import com.itfreer.arcgis.edit.DrawPointTool;
import com.itfreer.arcgis.edit.DrawPolyLineTool;
import com.itfreer.arcgis.edit.DrawPolygonTool;
import com.itfreer.arcgis.edit.DrawTool;
import com.itfreer.arcgis.edit.EditToolManager;
import com.itfreer.arcgis.query.AttributeListener;
import com.itfreer.arcgis.query.GetSelectFeatureListener;
import com.itfreer.arcgis.query.IdentifyListener2;
import com.itfreer.arcgis.symbol.SymbolStyleType;
import com.itfreer.arcgis.symbol.SymbolUtils;
import com.itfreer.ui.activity.BaseActivity;
import com.itfreer.ui.base.TextView;
import com.itfreer.utils.IntentUtils;
import com.itfreer.utils.LogUtils;
import com.itfreer.utils.MessageUtils;
import com.itfreer.utils.PathUtils;
import com.itfreer.utils.StringUtils;
import com.itfreer.utils.collection.SerializableMap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * 主界面，全屏展示
 */
public class MainActivity extends BaseActivity {

    private MapView mMapView;
    private Fragment searchFragment;
    private Fragment mapLayerFragment;
    private Fragment analyseFragment;


    //各种要求权限的回调状态码
    private static final Integer ACCESS_LOCAL_FILE = 1;
    private static final Integer OPEN_GPS = 2;


    //GPS定位相关
    private LocationDisplay locationDisplay=null;


    private final String[] reqPermission = new String[] { Manifest.permission.READ_EXTERNAL_STORAGE };
    //选择数据库文件路径
    String path ="";

    //是否开启I键查询功能
    Boolean hasOpenIdentify=false;


    //选择要素
    private Feature selectFeature;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //无title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //全屏
        getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
                WindowManager.LayoutParams. FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);

        //初始化破解许可
//        String licenseCode = "runtimelite,1000,rud9852553324,none,RP5X0H4AH4ALF5KHT145";
//        ArcGISRuntimeEnvironment.setLicense(licenseCode);

        // 地图对象
        mMapView = findViewById(R.id.mapView);
        ArcGISMap map = new ArcGISMap(Basemap.Type.TOPOGRAPHIC, 34.056295, -117.195800, 16);
        mMapView.setMap(map);
        mMapView.setAttributionTextVisible(false);

        // 缩小
        TextView zoonin =(TextView)findViewById(R.id.zooninText);
        zoonin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(mMapView!=null){
                    double scale = mMapView.getMapScale();
                    mMapView.setViewpointScaleAsync(scale*2);
                }
            }
        });

        // 放大
        TextView zoonout =(TextView)findViewById(R.id.zoonoutText);
        zoonout.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(mMapView!=null){
                    double scale = mMapView.getMapScale();
                    mMapView.setViewpointScaleAsync(scale*0.5);
                }
            }
        });

        // 我的
        TextView me =(TextView)findViewById(R.id.meText);
        me.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                goMyPage();
            }
        });

        // 信息
        TextView msg =(TextView)findViewById(R.id.msgText);
        msg.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                goMessagePage();
            }
        });

        // 查询
        TextView search =(TextView)findViewById(R.id.searchText);
        search.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(searchFragment==null){
                    searchFragment = new SearchFragment();
                    getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.fragment, searchFragment, "searchFragment")
                    .commit();
                } else {
                    getSupportFragmentManager()
                    .beginTransaction()
                    .show(searchFragment)
                    .commit();
                }
            }
        });

        // 图层
        LinearLayout mapLayer =(LinearLayout)findViewById(R.id.mapLayerText);
        mapLayer.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(mapLayerFragment==null){
                    mapLayerFragment = new MayLayerFragment();
                    getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.fragment, mapLayerFragment, "mapLayerFragment")
                    .commit();
                } else {
                    getSupportFragmentManager()
                    .beginTransaction()
                    .show(mapLayerFragment)
                    .commit();
                }
            }
        });

        // 任务
        LinearLayout task =(LinearLayout)findViewById(R.id.taskText);
        task.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                goTaskPage();
            }
        });

        // 巡护
        final RelativeLayout patrolContrl =(RelativeLayout)findViewById(R.id.patrolContrl);
        final TextView patrolContrlText =(TextView)findViewById(R.id.patrolContrlText);

        patrolContrl.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(patrolContrlText.getText()=="采集"){
                    patrolContrl.setBackgroundResource(R.drawable.navigation_circle_end);
                    patrolContrlText.setText("结束");
                } else {
                    patrolContrl.setBackgroundResource(R.drawable.navigation_circle);
                    patrolContrlText.setText("采集");
                }
            }
        });

        // 分析
        LinearLayout analyse =(LinearLayout)findViewById(R.id.analyse);
        analyse.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(analyseFragment==null){
                    analyseFragment = new AnalyseFragment();
                    getSupportFragmentManager()
                            .beginTransaction()
                            .add(R.id.fragment, analyseFragment, "analyseFragment")
                            .commit();
                } else {
                    getSupportFragmentManager()
                            .beginTransaction()
                            .show(analyseFragment)
                            .commit();
                }
            }
        });
    }
    /**
     * 接收调用外部视图回调结果回显
     * @param requestCode
     * @param resultCode
     * @param data
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        switch (requestCode)
        {
            case IntentUtils.FILE:
                if(resultCode ==0)
                    return;

                //获取选择文件路径
                Uri uri = data.getData();
                path = PathUtils.GetPathFromUri(uri);
                // android 23 需要实时校验权限
                if (ContextCompat.checkSelfPermission(MainActivity.this, reqPermission[0]) == PackageManager.PERMISSION_GRANTED)
                {
                    if(path.endsWith(".shp"))
                    {
                        loadShapeFile(path);
                    }
                    else
                    {
                        //加载数据库
                        loadGeodatabase(path);
                    }
                }
                else
                {
                    ActivityCompat.requestPermissions(MainActivity.this, reqPermission, ACCESS_LOCAL_FILE);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 加载数据库
     */
    private void loadGeodatabase(String path)
    {
        final Geodatabase geodatabase = GeodatabaseUtils.GetGeodatabaseByPath(path);
        geodatabase.loadAsync();
        geodatabase.addDoneLoadingListener(new Runnable()
        {
            @Override
            public void run()
            {
                if (geodatabase.getLoadStatus() == LoadStatus.LOADED)
                {
                    List<GeodatabaseFeatureTable> geodatabaseFeatureTables = GeodatabaseUtils.GetAllFeatureTables(geodatabase);
                    if(geodatabaseFeatureTables==null || geodatabaseFeatureTables.size() == 0)
                        return;

                    for(int i = 0;i<geodatabaseFeatureTables.size();i++)
                    {
                        GeodatabaseFeatureTable geodatabaseFeatureTable = geodatabaseFeatureTables.get(i);
                        geodatabaseFeatureTable.loadAsync();
                        //添加图层到地图中
                        MapUtils.AddGeodatabaseFeatureTable(mMapView,geodatabaseFeatureTable,true,"");
                    }
                }
                else
                {
                    MessageUtils.Show("数据加载失败！");
                    LogUtils.Print("数据库加载失败！", LogUtils.Lever.Info);
                }
            }
        });
    }

    /**
     * 加载本地shape数据
     * @param path
     */
    private void loadShapeFile(String path)
    {
        if(!path.endsWith(".shp"))
        {
            MessageUtils.Show("数据类型不正确！");
            return;
        }
        FeatureLayer featureLayer = LayerUtils.CreateFeatureLayerFormTable(FeatureTableUtils.GetFeatureTableFormShape(path));
        MapUtils.AddFeatureLayer(mMapView,featureLayer,true,"");
    }

    /**
     * 询问是否允许访问本地文件权限回调
     */
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        if(requestCode == ACCESS_LOCAL_FILE)
        {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                if (path.endsWith(".shp"))
                {
                    loadShapeFile(path);
                } else
                {
                    //加载本地数据库
                    loadGeodatabase(path);
                }
            } else
            {
                MessageUtils.Show("您拒绝访问本地文件！");
            }
        }
        else if(requestCode == OPEN_GPS)
        {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                locationDisplay.startAsync();
            }
            else
            {
                locationDisplay = null;
                MessageUtils.Show("您取消了开启定位功能！");
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if(searchFragment!=null && searchFragment.isVisible()){
                getSupportFragmentManager()
                .beginTransaction()
                .hide(searchFragment)
                .commit();
                return true;
            }
            if(mapLayerFragment!=null && mapLayerFragment.isVisible()){
                getSupportFragmentManager()
                .beginTransaction()
                .hide(mapLayerFragment)
                .commit();
                return true;
            }
            if(analyseFragment!=null && analyseFragment.isVisible()){
                getSupportFragmentManager()
                        .beginTransaction()
                        .hide(analyseFragment)
                        .commit();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 到我的界面
     */
    protected void goMyPage(){
        // 新建一个Intent对象
        Intent intent = new Intent();

        //将map数据添加到封装的myMap中
        final SerializableMap dataMap = new SerializableMap();
        dataMap.setMap(null);
        Bundle bundle = new Bundle();
        bundle.putSerializable("map", dataMap);
        intent.putExtras(bundle);

        // 指定intent要启动的类
        intent.setClass(MainActivity.this, MyActivity.class);
        // 启动一个新的Activity
        startActivity(intent);
    }

    /**
     * 到信息界面
     */
    protected void goMessagePage(){
        // 新建一个Intent对象
        Intent intent = new Intent();
        // 指定intent要启动的类
        intent.setClass(MainActivity.this, MessageActivity.class);
        // 启动一个新的Activity
        startActivity(intent);
    }

    /**
     * 到任务界面
     */
    protected void goTaskPage(){
        // 新建一个Intent对象
        Intent intent = new Intent();
        // 指定intent要启动的类
        intent.setClass(MainActivity.this, TaskActivity.class);
        // 启动一个新的Activity
        startActivity(intent);
    }

    /**
     * 打开数据库功能按钮
     * @param v
     */
    public void doClick(View v)
    {
        IntentUtils.openSelectFileIntent(this,"geodatabase","选择本地数据库");
    }

    /**
     * I键查询功能按钮
     * @param v
     */
    public void doClickIdentify(View v)
    {
        if(!hasOpenIdentify)
        {
            if(MapUtils.GetLayerCount(mMapView)>0)
            {
                hasOpenIdentify = true;
                MapUtils.Identify2(mMapView, new IdentifyListener2()
                {
                    @Override
                    public void execute(Map<String, List<Map<String, Object>>> data)
                    {
                        if(data == null || data.size() == 0)
                            return;

                        String message = "";
                        for (String key : data.keySet())
                        {
                            message+="图层："+key+"\n";
                            for(Integer i = 0;i<data.get(key).size();i++)
                            {
                                for (String key2 : data.get(key).get(i).keySet())
                                {
                                    message+=key2+"："+data.get(key).get(i).get(key2).toString()+"\n";
                                }
                                message+="\n";
                            }
                            message+="============================\n";
                        }
                        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
                        // set title
                        alertDialogBuilder.setTitle("I键查询结果");

                        // set dialog message
                        alertDialogBuilder
                                .setMessage(message)
                                .setCancelable(false)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener()
                                {
                                    @Override
                                    public void onClick(DialogInterface dialog, int id)
                                    {

                                    }
                                });
                        AlertDialog alertDialog = alertDialogBuilder.create();
                        alertDialog.show();
                    }
                });
            }
            else
            {
                MessageUtils.Show("没有可查询的图层对象！");
            }
        }
    }

    /**
     * 属性查询
     * @param v
     */
    public void doClickAttribute(View v)
    {
        if(MapUtils.GetLayerCount(mMapView)<=0)
        {
            MessageUtils.Show("没有可查询的图层，请先打开数据库！");
            return;
        }
        LinearLayout linearLayout = new LinearLayout(MainActivity.this);
        LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        linearLayout.setLayoutParams(params);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        final Spinner spinner = new Spinner(MainActivity.this);
        spinner.setLayoutParams(params);
        List<String> layerNames = MapUtils.GetLayerNames(mMapView);
        ArrayAdapter<String> adapter=new ArrayAdapter<>(this,android.R.layout.simple_spinner_item, layerNames);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        linearLayout.addView(spinner);

        final EditText editText = new EditText(MainActivity.this);
        editText.setLayoutParams(params);
        linearLayout.addView(editText);
        new AlertDialog.Builder(MainActivity.this)
                /* 弹出窗口的最上头文字 */
                .setTitle("设置查询条件").setView(linearLayout)
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialoginterface, int i)
                            {
                                dialoginterface.dismiss();
                                String condition = editText.getText().toString();
                                final String select = (String) spinner.getSelectedItem();
                                if(StringUtils.IsNullOrEmpty(select))
                                {
                                    MessageUtils.Show("请选择查询图层");
                                    return;
                                }
                                FeatureLayer featureLayer = MapUtils.GetFeatureLayerByName(mMapView, select);
                                if(featureLayer == null)
                                    return;

                                //清除地图中所有的选择元素
                                MapUtils.ClearSelection(mMapView);

                                final FeatureTable featureTable =featureLayer.getFeatureTable();
                                FeatureTableUtils.AttributeQuery(featureTable, condition, new AttributeListener()
                                {
                                    @Override
                                    public void execute(String tableName, List<Feature> data)
                                    {
                                        if(data ==null || data.size() == 0)
                                            return;
                                        FeatureLayer featureLayer = MapUtils.GetFeatureLayerByName(mMapView, select);
                                        for(Integer i = 0;i<data.size();i++)
                                        {
                                            featureLayer.selectFeature(data.get(i));
                                        }

                                        //设置当前地图范围
                                        Geometry temp = data.get(0).getGeometry();
                                        for(Integer i = 1;i<data.size();i++)
                                        {
                                            temp = GeometryEngine.union(temp,data.get(i).getGeometry());
                                        }
                                        mMapView.setViewpointGeometryAsync(temp.getExtent(), 10);
                                    }
                                });
                            }
                        })
                /* 设置弹出窗口的返回事件 */
                .setNegativeButton("取消",
                        new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialoginterface, int i)
                            {
                                dialoginterface.dismiss();
                            }
                        }).show();
    }

    /**
     * 添加shape数据到地图中
     * @param v
     */
    public void doClickAddShape(View v)
    {
        IntentUtils.openSelectFileIntent(this,"shp","打开本地shape数据");
    }

    /**
     * 属性更新
     * @param v
     */
    public void doClickUpdateAttribute(View v)
    {
        if(MapUtils.GetLayerCount(mMapView) == 0)
        {
            MessageUtils.Show("没有可查询的图层！");
            return;
        }
        MapUtils.Identify2(mMapView, new IdentifyListener2()
        {
            @Override
            public void execute(Map<String, List<Map<String, Object>>> data)
            {
                if(data == null || data.size() == 0)
                {
                    MessageUtils.Show("没有可更新的要素！");
                    return;
                }
                else if(data.size()>1)
                {
                    MessageUtils.Show("请选择单个图层的单个要素进行编辑！");
                    return;
                }
                else
                {
                    String layerName = "";
                    Map<String,Object> featureData = null;
                    for (String key : data.keySet())
                    {
                        List<Map<String,Object>> singleData = data.get(key);
                        if(singleData.size()>1)
                        {
                            MessageUtils.Show("请选择单个要素进行编辑！");
                            return;
                        }

                        layerName= key;
                        featureData = singleData.get(0);
                    }

                    final FeatureLayer featureLayer = MapUtils.GetFeatureLayerByName(mMapView,layerName);
                    if(featureLayer == null)
                        return;

                    String OIDFieldName = FeatureTableUtils.GetOIDFieldName(featureLayer.getFeatureTable());
                    Object objectId = featureData.get(OIDFieldName);
                    FeatureTableUtils.AttributeQuery(featureLayer.getFeatureTable(), OIDFieldName+" = " + objectId, new AttributeListener()
                    {
                        @Override
                        public void execute(String tableName, List<Feature> data)
                        {
                            Feature feature = data.get(0);
                            featureLayer.selectFeature(feature);
                            showCallout(feature,featureLayer.getFeatureTable());
                        }
                    });
                }
            }
        });
    }

    /**
     * 显示编辑对话框
     * @param feature 要素对象
     *                @param featureTable  图层对象
     */
    private void showCallout(final Feature feature,final FeatureTable featureTable)
    {
        Map<String,Object> attributes = feature.getAttributes();
        final LinearLayout linearLayout = new LinearLayout(MainActivity.this);
        LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        linearLayout.setLayoutParams(params);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        for (String key : attributes.keySet())
        {
            if(FeatureTableUtils.IsSystemField(featureTable,key))
                continue;

            LinearLayout linearLayout1 = new LinearLayout(MainActivity.this);
            linearLayout1.setLayoutParams(params);

            android.widget.TextView textView = new android.widget.TextView(MainActivity.this);
            textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            textView.setText(key+"：");
            linearLayout1.addView(textView);

            if(featureTable.getField(key).getFieldType() == Field.Type.TEXT)
            {
                EditText editText = new EditText(MainActivity.this);
                editText.setText(attributes.get(key).toString());
                editText.setTag(key);
                editText.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                linearLayout1.addView(editText);
                linearLayout.addView(linearLayout1);
            }
            else if(featureTable.getField(key).getFieldType() == Field.Type.INTEGER)
            {
                EditText editText = new EditText(MainActivity.this);
                editText.setText(attributes.get(key).toString());
                editText.setInputType(InputType.TYPE_CLASS_NUMBER);
                editText.setTag(key);
                editText.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                linearLayout1.addView(editText);
                linearLayout.addView(linearLayout1);
            }
            else if(featureTable.getField(key).getFieldType() == Field.Type.DOUBLE || featureTable.getField(key).getFieldType() == Field.Type.FLOAT )
            {
                EditText editText = new EditText(MainActivity.this);
                editText.setTag(key);
                editText.setText(attributes.get(key).toString());
                editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                editText.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                linearLayout1.addView(editText);
                linearLayout.addView(linearLayout1);
            }
        }
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
        alertDialogBuilder.setTitle("属性编辑");
        alertDialogBuilder.setCancelable(true).
                setView(linearLayout)
                .setPositiveButton("确定", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int id)
                    {
                        for(Integer i = 0;i<linearLayout.getChildCount();i++)
                        {
                            LinearLayout tempLinearLayout = (LinearLayout) linearLayout.getChildAt(i);
                            EditText editText = (EditText) tempLinearLayout.getChildAt(1);
                            String fieldName = (String) editText.getTag();
                            if(feature.getFeatureTable().getField(fieldName).getFieldType().equals(Field.Type.TEXT))
                                feature.getAttributes().put(fieldName,editText.getText().toString());
                            else if(feature.getFeatureTable().getField(fieldName).getFieldType().equals(Field.Type.INTEGER))
                                feature.getAttributes().put(fieldName,Integer.parseInt(editText.getText().toString()));
                        }

                        if(!featureTable.canUpdate(feature))
                        {
                            MessageUtils.Show("当前数据类型无法进行编辑，目前arcgis for android 只能针对shape数据进行编辑！");
                            return;
                        }

                        final ListenableFuture<Void> updateFeatures= featureTable.updateFeatureAsync(feature);
                        // 在操作完成的监听事件中判断操作是否成功
                        updateFeatures.addDoneListener(new Runnable() {
                            @Override
                            public void run()
                            {
                                try
                                {
                                    updateFeatures.get();
                                    if (updateFeatures.isDone())
                                    {
                                        MessageUtils.Show("要素更新成功！");
                                    }
                                }
                                catch(Exception ex)
                                {
                                    ex.printStackTrace();
                                }
                            }
                        });
                    }
                });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    /**
     * 绘制点要素
     * @param v
     */
    public void doClickDrawPoint(View v)
    {
        List<FeatureLayer> featureLayers = MapUtils.GetPointFeatureLayers(mMapView);
        if (featureLayers == null || featureLayers.size() == 0)
        {
            MessageUtils.Show("没有可编辑的点图层");
            return;
        }
        if(!featureLayers.get(0).getFeatureTable().canAdd())
        {
            MessageUtils.Show("当前图层不可添加要素");
            return;
        }
        Button button =(Button)v;
        if(button.getText().equals("保存"))
        {
            button.setText("绘制点要素");
            FeatureTableUtils.AddFeature(EditToolManager.GetCurrentTool().GetGeometry(),null,featureLayers.get(0).getFeatureTable());
            EditToolManager.GetCurrentTool().Clear();
        }
        else
        {
            button.setText("保存");
            DrawPointTool drawTool = new DrawPointTool();
            drawTool.Draw(mMapView,null);
        }
    }

    /**
     * 绘制线要素
     * @param v
     */
    public void doClickDrawPolyline(View v)
    {
        List<FeatureLayer> featureLayers = MapUtils.GetPolyLineFeatureLayers(mMapView);
        if (featureLayers == null || featureLayers.size() == 0)
        {
            MessageUtils.Show("没有可编辑的线图层");
            return;
        }
        if(!featureLayers.get(0).getFeatureTable().canAdd())
        {
            MessageUtils.Show("当前图层不可添加要素");
            return;
        }
        Button button =(Button)v;
        if(button.getText().equals("保存"))
        {
            button.setText("绘制线要素");
            FeatureTableUtils.AddFeature(EditToolManager.GetCurrentTool().GetGeometry(),null,featureLayers.get(0).getFeatureTable());
            EditToolManager.GetCurrentTool().Clear();
        }
        else
        {
            button.setText("保存");
            DrawPolyLineTool drawTool = new DrawPolyLineTool();
            drawTool.Draw(mMapView,null);
        }
    }

    /**
     * 绘制面要素
     * @param v
     */
    public void doClickDrawPolygon(View v)
    {
        List<FeatureLayer> featureLayers = MapUtils.GetPolygonFeatureLayers(mMapView);
        if (featureLayers == null || featureLayers.size() == 0)
        {
            MessageUtils.Show("没有可编辑的面图层");
            return;
        }
        if(!featureLayers.get(0).getFeatureTable().canAdd())
        {
            MessageUtils.Show("当前图层不可添加要素");
            return;
        }
        Button button =(Button)v;
        if(button.getText().equals("保存"))
        {
            button.setText("绘制面要素");
            FeatureTableUtils.AddFeature(EditToolManager.GetCurrentTool().GetGeometry(),null,featureLayers.get(0).getFeatureTable());
            EditToolManager.GetCurrentTool().Clear();
        }
        else
        {
            button.setText("保存");
            DrawPolygonTool drawTool = new DrawPolygonTool();
            drawTool.Draw(mMapView,null);
        }
    }

    /**
     * 放大
     * @param v
     */
    public void doClickZoomIn(View v)
    {
        MapViewUtils.DefaultZoomIn(mMapView);
    }

    /**
     * 缩小
     * @param v
     */
    public void doClickZoomOut(View v)
    {
        MapViewUtils.DefaultZoomOut(mMapView);
    }

    /**
     * 控制图层可见
     * @param v
     */
    public void doClickShowLayer(View v)
    {
        Integer count = MapUtils.GetLayerCount(mMapView);
        if(count<1)
        {
            MessageUtils.Show("请保证当期地图中存在图层");
            return;
        }
        MapViewUtils.ShowOrHiddenLayer(mMapView,0);
    }

    /**
     * 调整图层顺序
     * @param v
     */
    public void doClickChangeOrder(View v)
    {
        Integer count = MapUtils.GetLayerCount(mMapView);
        if(count<2)
        {
            MessageUtils.Show("请保证当前图层个数不少于2");
            return;
        }
        Layer layer =MapUtils.GetLayerByIndex(mMapView,0);
        MapViewUtils.ChangeLayerOrder(mMapView,layer,1);
    }

    /**
     * 地图定位
     * @param v
     */
    public void doClickLocation(View v)
    {
        if(locationDisplay !=null)
        {
            locationDisplay.setAutoPanMode(LocationDisplay.AutoPanMode.RECENTER);
            if (!locationDisplay.isStarted())
                locationDisplay.startAsync();
        }
        else
        {
            final String[] reqPermissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
            locationDisplay = mMapView.getLocationDisplay();
            locationDisplay.setAutoPanMode(LocationDisplay.AutoPanMode.RECENTER);
            if (!locationDisplay.isStarted())
                locationDisplay.startAsync();
            locationDisplay.addDataSourceStatusChangedListener(new LocationDisplay.DataSourceStatusChangedListener()
            {
                @Override
                public void onStatusChanged(LocationDisplay.DataSourceStatusChangedEvent dataSourceStatusChangedEvent)
                {
                    if (dataSourceStatusChangedEvent.isStarted())
                        return;
                    if (dataSourceStatusChangedEvent.getError() == null)
                        return;

                    boolean permissionCheck1 = ContextCompat.checkSelfPermission(mMapView.getContext(), reqPermissions[0]) == PackageManager.PERMISSION_GRANTED;
                    boolean permissionCheck2 = ContextCompat.checkSelfPermission(mMapView.getContext(), reqPermissions[1]) == PackageManager.PERMISSION_GRANTED;

                    if (!(permissionCheck1 && permissionCheck2))
                    {
                        ActivityCompat.requestPermissions((Activity) mMapView.getContext(), reqPermissions, OPEN_GPS);
                    }
                    else
                    {
                        locationDisplay = null;
                    }
                }
            });
        }
    }

    /**
     * 点元素编辑
     * @param v
     */
    public void doEditPoint(View v)
    {
        final List<FeatureLayer> featureLayers = MapUtils.GetPointFeatureLayers(mMapView);
        if (featureLayers == null || featureLayers.size() == 0)
        {
            MessageUtils.Show("没有可编辑的点图层");
            return;
        }
        if(!featureLayers.get(0).getFeatureTable().canAdd())
        {
            MessageUtils.Show("当前图层不可编辑要素");
            return;
        }
        final Button button =(Button)v;
        if(button.getText().equals("保存"))
        {
            button.setText("点编辑");
            selectFeature.setGeometry(EditToolManager.GetCurrentTool().GetGeometry());
            FeatureTableUtils.UpdateFeature(selectFeature.getFeatureTable(),selectFeature);
            EditToolManager.GetCurrentTool().Clear();
        }
        else
        {
            final ListenableFuture<FeatureQueryResult> features = featureLayers.get(0).getSelectedFeaturesAsync();
            features.addDoneListener(new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        List<Feature> selectFeatures = new ArrayList<>();
                        for (Feature feature : features.get())
                            selectFeatures.add(feature);

                        if(selectFeatures.size() == 0)
                        {
                            MessageUtils.Show("请选择一个数据");
                            return;
                        }
                        button.setText("保存");
                        selectFeature = selectFeatures.get(0);

                        DrawPointTool drawTool = new DrawPointTool();
                        drawTool.Draw(mMapView,selectFeatures.get(0).getGeometry());
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /**
     * 线元素编辑
     * @param v
     */
    public void doEditPolyline(View v)
    {
        final List<FeatureLayer> featureLayers = MapUtils.GetPolyLineFeatureLayers(mMapView);
        if (featureLayers == null || featureLayers.size() == 0)
        {
            MessageUtils.Show("没有可编辑的线图层");
            return;
        }
        if(!featureLayers.get(0).getFeatureTable().canAdd())
        {
            MessageUtils.Show("当前图层不可编辑要素");
            return;
        }
        final Button button =(Button)v;
        if(button.getText().equals("保存"))
        {
            button.setText("线编辑");
            selectFeature.setGeometry(EditToolManager.GetCurrentTool().GetGeometry());
            FeatureTableUtils.UpdateFeature(selectFeature.getFeatureTable(),selectFeature);
            EditToolManager.GetCurrentTool().Clear();
        }
        else
        {
            final ListenableFuture<FeatureQueryResult> features = featureLayers.get(0).getSelectedFeaturesAsync();
            features.addDoneListener(new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        List<Feature> selectFeatures = new ArrayList<>();
                        for (Feature feature : features.get())
                            selectFeatures.add(feature);

                        if(selectFeatures.size() == 0)
                        {
                            MessageUtils.Show("请选择一个数据");
                            return;
                        }
                        button.setText("保存");
                        selectFeature = selectFeatures.get(0);
                        DrawPolyLineTool drawTool = new DrawPolyLineTool();
                        drawTool.Draw(mMapView,selectFeatures.get(0).getGeometry());
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /**
     * 面元素编辑
     * @param v
     */
    public void doEditPolygon(View v)
    {
        final List<FeatureLayer> featureLayers = MapUtils.GetPolygonFeatureLayers(mMapView);
        if (featureLayers == null || featureLayers.size() == 0)
        {
            MessageUtils.Show("没有可编辑的面图层");
            return;
        }
        if(!featureLayers.get(0).getFeatureTable().canAdd())
        {
            MessageUtils.Show("当前图层不可编辑要素");
            return;
        }
        final Button button =(Button)v;
        if(button.getText().equals("保存"))
        {
            button.setText("面编辑");
            selectFeature.setGeometry(EditToolManager.GetCurrentTool().GetGeometry());
            FeatureTableUtils.UpdateFeature(selectFeature.getFeatureTable(),selectFeature);
            EditToolManager.GetCurrentTool().Clear();
        }
        else
        {
            final ListenableFuture<FeatureQueryResult> features = featureLayers.get(0).getSelectedFeaturesAsync();
            features.addDoneListener(new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        List<Feature> selectFeatures = new ArrayList<>();
                        for (Feature feature : features.get())
                            selectFeatures.add(feature);

                        if(selectFeatures.size() == 0)
                        {
                            MessageUtils.Show("请选择一个数据");
                            return;
                        }
                        button.setText("保存");
                        selectFeature = selectFeatures.get(0);
                        DrawPolygonTool drawTool = new DrawPolygonTool();
                        drawTool.Draw(mMapView,selectFeatures.get(0).getGeometry());
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /**
     * 修改点样式
     * @param v
     */
    public void doClickChangePointSymbol(View v)
    {
        List<FeatureLayer> featureLayers = MapUtils.GetPointFeatureLayers(mMapView);
        if (featureLayers == null || featureLayers.size() == 0)
        {
            MessageUtils.Show("没有可编辑的点图层");
            return;
        }
        Button button =(Button)v;
        if(button.getText().equals("还原"))
        {
            button.setText("修改点样式");
            LayerUtils.ResetSymbol(featureLayers.get(0));
        }
        else
        {
            button.setText("还原");
            LayerUtils.UpdatePointLayerStyle(featureLayers.get(0),"#FFB300",10);
        }
    }

    /**
     * 修改线样式
     * @param v
     */
    public void doClickChangeLineSymbol(View v)
    {
        List<FeatureLayer> featureLayers = MapUtils.GetPolyLineFeatureLayers(mMapView);
        if (featureLayers == null || featureLayers.size() == 0)
        {
            MessageUtils.Show("没有可编辑的线图层");
            return;
        }
        Button button =(Button)v;
        if(button.getText().equals("还原"))
        {
            button.setText("修改线样式");
            LayerUtils.ResetSymbol(featureLayers.get(0));
        }
        else
        {
            button.setText("还原");
            LayerUtils.UpdateLineLayerStyle(featureLayers.get(0),"#FFB300",10);
        }
    }

    /**
     * 修改面样式
     * @param v
     */
    public void doClickChangePolygonSymbol(View v)
    {
        List<FeatureLayer> featureLayers = MapUtils.GetPolygonFeatureLayers(mMapView);
        if (featureLayers == null || featureLayers.size() == 0)
        {
            MessageUtils.Show("没有可编辑的面图层");
            return;
        }
        Button button =(Button)v;
        if(button.getText().equals("还原"))
        {
            button.setText("修改面样式");
            LayerUtils.ResetSymbol(featureLayers.get(0));
        }
        else
        {
            button.setText("还原");
            SimpleLineSymbol lineSymbol = SymbolUtils.GetPolylineSymbol(SymbolStyleType.PolylineType.SOLID, com.itfreer.utils.ColorUtils.Hex2Int("#81C784"),10);
            LayerUtils.UpdatePolygonLayerStyle(featureLayers.get(0),"#FFB300",10,lineSymbol);
        }
    }

    /**
     * 点选要素
     * @param v
     */
    public void doClickSelect(View v)
    {
        final List<FeatureLayer> featureLayers = MapUtils.GetFeatureLayers(mMapView);
        if(featureLayers == null || featureLayers.size() == 0)
        {
            MessageUtils.Show("没有可选择的图层");
            return;
        }

        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mMapView)
        {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e)
            {
                Point clickPoint = mMapView.screenToLocation(new android.graphics.Point(Math.round(e.getX()), Math.round(e.getY())));
                for(Integer i = 0;i<featureLayers.size();i++)
                    LayerUtils.SelectFeatures(clickPoint,mMapView,featureLayers.get(i));
                return super.onSingleTapConfirmed(e);
            }
        });
    }

    /**
     * 删除选择要素，默认只处理第一个图层的选择要素
     * @param v
     */
    public void doDeleteSelectFeature(View v)
    {
        final List<FeatureLayer> featureLayers = MapUtils.GetFeatureLayers(mMapView);
        if(featureLayers == null || featureLayers.size() == 0)
        {
            MessageUtils.Show("没有可选择的图层");
            return;
        }

        for(Integer i = 0;i<featureLayers.size();i++)
        {
            LayerUtils.GetSelectFeature(featureLayers.get(i), new GetSelectFeatureListener()
            {
                @Override
                public void execute(FeatureLayer featureLayer, ListenableFuture<FeatureQueryResult> features)
                {
                    try
                    {
                        for (Feature feature : features.get())
                        {
                            FeatureTableUtils.DeleteFeature(featureLayer.getFeatureTable(),feature);
                        }
                    } catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    } catch (ExecutionException e)
                    {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /**
     * 线分割
     * @param v
     */
    public void doClickLineCut(final View v)
    {
        List<FeatureLayer> featureLayers = MapUtils.GetPolyLineFeatureLayers(mMapView);
        if (featureLayers == null || featureLayers.size() == 0)
        {
            MessageUtils.Show("没有可编辑的线图层");
            return;
        }
        final Button button =(Button)v;
        if(button.getText().equals("保存"))
        {
            button.setText("线分割");
            //面分割必须保证图形的坐标系一致
            Geometry geometry = EditToolManager.GetCurrentTool().GetGeometry();
            if(geometry == null || geometry.isEmpty())
                return;
            geometry = GeometryEngine.project(geometry,selectFeature.getGeometry().getSpatialReference());
            List<Geometry> geometries =  GeometryEngine.cut(selectFeature.getGeometry(),(Polyline) geometry);
            if(geometries!=null && geometries.size()>1)
            {
                //保留最大的图形为之前要素的图形，其他的geometry 作为新增使用
                Geometry maxGeometry = geometries.get(0);
                Integer index = 0;
                for (Integer i = 1; i < geometries.size(); i++)
                {
                    if(GeometryEngine.length((Polyline) geometries.get(i))>GeometryEngine.length((Polyline) maxGeometry))
                    {
                        maxGeometry = geometries.get(i);
                        index= i;
                    }
                }
                selectFeature.setGeometry(maxGeometry);
                FeatureTableUtils.UpdateFeature(selectFeature.getFeatureTable(),selectFeature);
                for(Integer i = 0;i<geometries.size();i++)
                {
                    if(i!=index)
                        FeatureTableUtils.AddFeature(geometries.get(i),null,selectFeature.getFeatureTable());
                }
            }

            EditToolManager.GetCurrentTool().Clear();
        }
        else
        {
            LayerUtils.GetSelectFeature(featureLayers.get(0), new GetSelectFeatureListener()
            {
                @Override
                public void execute(FeatureLayer featureLayer, ListenableFuture<FeatureQueryResult> features)
                {
                    try
                    {
                        List<Feature> selectFeatues = new ArrayList<>();
                        for (Feature feature : features.get())
                        {
                            selectFeatues.add(feature);
                            if(selectFeatues.size()>1)
                            {
                                MessageUtils.Show("请选择单个要素进行分割！");
                                break;
                            }
                        }
                        if(selectFeatues.size() == 1)
                        {
                            selectFeature = selectFeatues.get(0);
                            button.setText("保存");
                            DrawPolyLineTool drawTool = new DrawPolyLineTool();
                            drawTool.Draw(mMapView,null);
                        }
                        else
                        {
                            MessageUtils.Show("请选择一个线要素！");
                        }
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                    catch (ExecutionException e)
                    {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /**
     * 线分割
     * @param v
     */
    public void doClickPolygonCut(View v)
    {
        List<FeatureLayer> featureLayers = MapUtils.GetPolygonFeatureLayers(mMapView);
        if (featureLayers == null || featureLayers.size() == 0)
        {
            MessageUtils.Show("没有可编辑的面图层");
            return;
        }
        final Button button =(Button)v;
        if(button.getText().equals("保存"))
        {
            button.setText("面分割");
            //面分割必须保证图形的坐标系一致
            Geometry geometry = EditToolManager.GetCurrentTool().GetGeometry();
            if(geometry == null || geometry.isEmpty())
                return;
            geometry = GeometryEngine.project(geometry,selectFeature.getGeometry().getSpatialReference());
            List<Geometry> geometries =  GeometryEngine.cut(selectFeature.getGeometry(),(Polyline) geometry);
            if(geometries!=null && geometries.size()>1)
            {
                //保留最大的图形为之前要素的图形，其他的geometry 作为新增使用
                Geometry maxGeometry = geometries.get(0);
                Integer index = 0;
                for (Integer i = 1; i < geometries.size(); i++)
                {
                    if(GeometryEngine.area((Polygon) geometries.get(i))>GeometryEngine.area((Polygon) maxGeometry))
                    {
                        maxGeometry = geometries.get(i);
                        index= i;
                    }
                }
                selectFeature.setGeometry(maxGeometry);
                FeatureTableUtils.UpdateFeature(selectFeature.getFeatureTable(),selectFeature);
                for(Integer i = 0;i<geometries.size();i++)
                {
                    if(i!=index)
                        FeatureTableUtils.AddFeature(geometries.get(i),null,selectFeature.getFeatureTable());
                }
            }

            EditToolManager.GetCurrentTool().Clear();
        }
        else
        {
            LayerUtils.GetSelectFeature(featureLayers.get(0), new GetSelectFeatureListener()
            {
                @Override
                public void execute(FeatureLayer featureLayer, ListenableFuture<FeatureQueryResult> features)
                {
                    try
                    {
                        List<Feature> selectFeatues = new ArrayList<>();
                        for (Feature feature : features.get())
                        {
                            selectFeatues.add(feature);
                            if(selectFeatues.size()>1)
                            {
                                MessageUtils.Show("请选择单个要素进行分割！");
                                break;
                            }
                        }
                        if(selectFeatues.size() == 1)
                        {
                            selectFeature = selectFeatues.get(0);
                            button.setText("保存");
                            DrawPolyLineTool drawTool = new DrawPolyLineTool();
                            drawTool.Draw(mMapView,null);
                        }
                        else
                        {
                            MessageUtils.Show("请选择一个面要素！");
                        }
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                    catch (ExecutionException e)
                    {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /**
     * 清除选择
     * @param v
     */
    public void doClickClearSelection(View v)
    {
        List<FeatureLayer> featureLayers = MapUtils.GetFeatureLayers(mMapView);
        if(featureLayers == null || featureLayers.size() == 0)
        {
            MessageUtils.Show("没有需要清除的图层！");
            return;
        }

        for(Integer i = 0;i<featureLayers.size();i++)
        {
            featureLayers.get(i).clearSelection();
        }
    }

    /**
     * 移除地图中第一个图层
     * @param v
     */
    public void doClickRemoveLayer(View v)
    {
        List<Layer> layers = mMapView.getMap().getOperationalLayers();
        if(layers.size()==0)
        {
            MessageUtils.Show("没有可移除的图层！");
            return;
        }
        mMapView.getMap().getOperationalLayers().remove(0);
    }

    /**
     * 线测量
     * @param v
     */
    public void doClickMearueLine(View v)
    {
        Button button =(Button)v;
        if(button.getText().equals("完成"))
        {
            button.setText("线测量");
            Geometry geometry = EditToolManager.GetCurrentTool().GetGeometry();
            if(geometry == null || geometry.isEmpty())
            {
                EditToolManager.GetCurrentTool().Clear();
                return;
            }
            Double lengthMi = GeometryEngine.length((Polyline) geometry);
            MessageUtils.Show("线测量长度："+lengthMi);
            EditToolManager.GetCurrentTool().Clear();
        }
        else
        {
            button.setText("完成");
            DrawPolyLineTool drawTool = new DrawPolyLineTool();
            drawTool.Draw(mMapView,null);
        }
    }

    /**
     * 线测量
     * @param v
     */
    public void doClickMearueProgen(View v)
    {
        Button button =(Button)v;
        if(button.getText().equals("完成"))
        {
            button.setText("面测量");
            Geometry geometry = EditToolManager.GetCurrentTool().GetGeometry();
            if(geometry ==null || geometry.isEmpty())
            {
                EditToolManager.GetCurrentTool().Clear();
                return;
            }
            Double lengthMi = GeometryEngine.area((Polygon) geometry);
            MessageUtils.Show("面测量大小："+lengthMi);
            EditToolManager.GetCurrentTool().Clear();
        }
        else
        {
            button.setText("完成");
            DrawFreePolygonTool drawTool = new DrawFreePolygonTool();
            drawTool.Draw(mMapView,null);
        }
    }

    /**
     * 绘制自由线
     * @param v
     */
    public void doClickCreateFreeLine(View v)
    {
        List<FeatureLayer> featureLayers = MapUtils.GetPolyLineFeatureLayers(mMapView);
        if (featureLayers == null || featureLayers.size() == 0)
        {
            MessageUtils.Show("没有可编辑的线图层");
            return;
        }
        if(!featureLayers.get(0).getFeatureTable().canAdd())
        {
            MessageUtils.Show("当前图层不可添加要素");
            return;
        }
        Button button =(Button)v;
        if(button.getText().equals("保存"))
        {
            button.setText("绘制自由线");
            FeatureTableUtils.AddFeature(EditToolManager.GetCurrentTool().GetGeometry(),null,featureLayers.get(0).getFeatureTable());
            EditToolManager.GetCurrentTool().Clear();
        }
        else
        {
            button.setText("保存");
            DrawFreePolyLineTool drawTool = new DrawFreePolyLineTool();
            drawTool.Draw(mMapView,null);
        }
    }

    /**
     * 绘制自由面
     * @param v
     */
    public void doClickCreateFreePolygon(View v)
    {
        List<FeatureLayer> featureLayers = MapUtils.GetPolygonFeatureLayers(mMapView);
        if (featureLayers == null || featureLayers.size() == 0)
        {
            MessageUtils.Show("没有可编辑的面图层");
            return;
        }
        if(!featureLayers.get(0).getFeatureTable().canAdd())
        {
            MessageUtils.Show("当前图层不可添加要素");
            return;
        }
        Button button =(Button)v;
        if(button.getText().equals("保存"))
        {
            button.setText("绘制自由面");
            FeatureTableUtils.AddFeature(EditToolManager.GetCurrentTool().GetGeometry(),null,featureLayers.get(0).getFeatureTable());
            EditToolManager.GetCurrentTool().Clear();
        }
        else
        {
            button.setText("保存");
            DrawFreePolygonTool drawTool = new DrawFreePolygonTool();
            drawTool.Draw(mMapView,null);
        }
    }

    /**
     * 编辑回退
     * @param v
     */
    public void doClickEditBack(View v)
    {
        DrawTool drawTool = EditToolManager.GetCurrentTool();
        if(drawTool == null)
        {
            MessageUtils.Show("请先绘制元素");
            return;
        }

        drawTool.Back();
    }

    /**
     * 编辑回退
     * @param v
     */
    public void doClickEditForwad(View v)
    {
        DrawTool drawTool = EditToolManager.GetCurrentTool();
        if(drawTool == null)
        {
            MessageUtils.Show("请先绘制元素");
            return;
        }

        drawTool.Forwad();
    }

    /**
     * 编辑回退
     * @param v
     */
    public void doClickEditDrop(View v)
    {
        DrawTool drawTool = EditToolManager.GetCurrentTool();
        if(drawTool == null)
        {
            MessageUtils.Show("请先绘制元素");
            return;
        }

        drawTool.Clear();
    }

    /**
     * 显示标注
     * @param v
     */
    public void doClickShowLabel(View v)
    {
        List<FeatureLayer>  featureLayers = MapUtils.GetFeatureLayers(mMapView);
        if(featureLayers == null || featureLayers.size() == 0)
        {
            MessageUtils.Show("请先加载图层！");
            return;
        }

        String color = "#1E90FF";
        LayerUtils.ShowFeatureLayerLabel(featureLayers.get(0),color,FeatureTableUtils.GetOIDField(featureLayers.get(0).getFeatureTable()));
    }

    /**
     * 隐藏标注
     * @param v
     */
    public void doClickHiddenLabel(View v)
    {
        List<FeatureLayer>  featureLayers = MapUtils.GetFeatureLayers(mMapView);
        if(featureLayers == null || featureLayers.size() == 0)
        {
            MessageUtils.Show("请先加载图层！");
            return;
        }
        LayerUtils.HiddenFeatureLayerLabel(featureLayers.get(0));
    }


    @Override
    protected void onPause(){
        mMapView.pause();
        super.onPause();
    }

    @Override
    protected void onResume(){
        super.onResume();
        mMapView.resume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.dispose();
    }

    /**
     * 返回时，是否可以退出
     * @return
     */
    protected boolean canExit(){
        return true;
    }
}
